define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'clothmaking_plan/index' + location.search,
                    add_url: 'clothmaking_plan/add',
                    edit_url: 'clothmaking_plan/edit',
                    del_url: 'clothmaking_plan/del',
                    multi_url: 'clothmaking_plan/multi',
                    import_url: 'clothmaking_plan/import',
                    print_url: 'clothmaking_plan/print',
                    table: 'clothmaking_plan',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'weigh',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'name', title: __('Name'), operate: 'LIKE'},
                        {field: 'id', title: __('Id')},
                        {field: 'product_id', title: __('Product_id')},
                        {field: 'order_id', title: __('Order_id')},
                        {field: 'recipe_id', title: __('Recipe_id')},
                        {field: 'formula_process_id', title: __('Formula_process_id')},
                        {field: 'coating_process_id', title: __('Coating_process_id')},
                        // {field: 'plc_tech.name', title: __('Plc_tech_id')},
                        {field: 'product_inspection_id', title: __('Product_inspection_id')},
                        // {field: 'packing_inspection_id	', title: __('Packing_inspection_id')},
                        {field: 'quantity', title: __('Quantity')},
                        {field: 'kettle_id', title: __('Kettle_id')},
                        {field: 'status', title: __('Status'), searchList: {"normal":__('Normal'),"notstarted":__('Notstarted'),"completed":__('Completed')}, formatter: Table.api.formatter.status},
                        {field: 'weigh', title: __('Weigh'), operate: false},
                        {field: 'mark', title: __('Mark'), operate: 'LIKE'},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'production_recipe_process_id', title: __('Production_recipe_process_id')},
                        {field: 'production_coating_process_id', title: __('Production_coating_process_id')},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, 
                    formatter: function (value, row, index) {
                        var table = this.table;
                        var buttons = Table.api.formatter.operate.call(this, value, row, index);
                        // 始终显示打印按钮，但添加状态属性
                        return '<a href="javascript:;" class="btn btn-xs btn-info btn-printone" data-id="' + row.id + '" data-status="' + row.status + '" title="打印"><i class="fa fa-print"></i> 打印</a> ' + buttons;
                    }
                }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            
            // 自定义操作列格式化器
            table.on('post-body.bs.table', function (e, data) {
                $(".btn-printone").data("area", ["800px", "600px"]);
                $(".btn-printone").on('click', function () {
                    var id = $(this).data("id");
                    var status = $(this).data("status");
                    
                    // 检查状态是否为已完成
                    if (status !== 'completed') {
                        Toastr.error('生产计划未完成，无法打印');
                        return false;
                    }
                    
                    Fast.api.open($.fn.bootstrapTable.defaults.extend.print_url + "?ids=" + id, __('Print'), {
                        area: ["800px", "600px"],
                        callback: function (data) {
                            table.bootstrapTable('refresh');
                        }
                    });
                });
            });
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        initCustomerDemandTable: function() {
            // 客户需求ID变化时加载表格数据
            $("#customer-demand-table").bootstrapTable({
                url: 'aaa',
                method: 'get',
                columns: [
                    {field: 'demand_id', title: '需求ID'},
                    {field: 'id', title: '产品ID'},
                    {field: 'name', title: '产品名称'},
                    {field: 'quantity',title: '数量',}
                ]
            });
        },
        loadTableData: function(order_id) {
            $.ajax({
                url: 'clothmaking_orders/getTableData',
                data: {order_id: order_id},
                success: function (res) {
                    $("#customer-demand-table").bootstrapTable('load', res);
                }
            });
        },
        loadRecipeDetails: function(recipe_id) {
            $("#recipe_detail").empty();
            $.ajax({
                url: 'clothmaking_recipe/getRecipeById',
                data: {id: recipe_id},
                success: function (res) {
                    ingredient_details = res.data.ingredient_details;
                    for (key in ingredient_details){
                        $("#recipe_detail").append(
                            '<div style="float: left;margin-bottom: 10px;"><input class="form-control" type="text" style="width: 30%; margin-right:10px" readonly value="'+key+'"><input class="form-control" type="text" style="width: 30%;" readonly value="'+ingredient_details[key]+'"></div>'
                        )
                    }
                }
            });
        },
        api: {
            bindevent: function () {
                Controller.loadTableData($("#c-order_id").val());
                Controller.loadRecipeDetails($("#c-recipe_id").val());
                $("#c-order_id").data("eSelect", function(data){
                    Controller.loadTableData(data.id);
                });
                $("#c-recipe_id").data("eSelect", function(data){
                    Controller.loadRecipeDetails(data.id);
                });

                Controller.initCustomerDemandTable();
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
